"""
配置管理器
"""
import os
import json
from typing import Dict, Any, Optional
from pathlib import Path
from config.settings import settings
from base.logger_manager import LoggerManager


class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        self.logger = LoggerManager.get_logger("config_manager")
        self.config_dir = Path("config")
        self.config_dir.mkdir(exist_ok=True)
    
    def load_config(self, config_name: str) -> Optional[Dict[str, Any]]:
        """加载配置文件"""
        try:
            config_file = self.config_dir / f"{config_name}.json"
            if not config_file.exists():
                self.logger.warning(f"配置文件不存在: {config_file}")
                return None
            
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
            
            self.logger.info(f"成功加载配置: {config_name}")
            return config
            
        except Exception as e:
            self.logger.error(f"加载配置失败: {config_name}, 错误: {str(e)}")
            return None
    
    def save_config(self, config_name: str, config_data: Dict[str, Any]) -> bool:
        """保存配置文件"""
        try:
            config_file = self.config_dir / f"{config_name}.json"
            
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
            
            self.logger.info(f"成功保存配置: {config_name}")
            return True
            
        except Exception as e:
            self.logger.error(f"保存配置失败: {config_name}, 错误: {str(e)}")
            return False
    
    def get_platform_config(self, platform: str) -> Dict[str, Any]:
        """获取平台配置"""
        config = self.load_config(f"platform_{platform}")
        if not config:
            # 返回默认配置
            return self._get_default_platform_config(platform)
        return config
    
    def save_platform_config(self, platform: str, config_data: Dict[str, Any]) -> bool:
        """保存平台配置"""
        return self.save_config(f"platform_{platform}", config_data)
    
    def get_search_config(self) -> Dict[str, Any]:
        """获取搜索配置"""
        config = self.load_config("search")
        if not config:
            return self._get_default_search_config()
        return config
    
    def save_search_config(self, config_data: Dict[str, Any]) -> bool:
        """保存搜索配置"""
        return self.save_config("search", config_data)
    
    def get_proxy_config(self) -> Dict[str, Any]:
        """获取代理配置"""
        config = self.load_config("proxy")
        if not config:
            return self._get_default_proxy_config()
        return config
    
    def save_proxy_config(self, config_data: Dict[str, Any]) -> bool:
        """保存代理配置"""
        return self.save_config("proxy", config_data)
    
    def _get_default_platform_config(self, platform: str) -> Dict[str, Any]:
        """获取默认平台配置"""
        default_configs = {
            "linkedin": {
                "base_url": "https://www.linkedin.com",
                "login_url": "https://www.linkedin.com/login",
                "search_url": "https://www.linkedin.com/search/results/people/",
                "selectors": {
                    "login_form": "#username",
                    "password_form": "#password",
                    "login_button": ".btn__primary--large",
                    "search_input": ".search-global-typeahead__input",
                    "search_button": ".search-global-typeahead__button",
                    "profile_cards": ".entity-result__item",
                    "profile_name": ".entity-result__title-text a",
                    "profile_headline": ".entity-result__summary",
                    "profile_location": ".entity-result__secondary-subtitle",
                    "next_page": ".artdeco-pagination__button--next"
                },
                "wait_timeouts": {
                    "page_load": 30,
                    "element_wait": 10,
                    "login_wait": 600
                },
                "pagination": {
                    "max_pages": 10,
                    "results_per_page": 10
                }
            },
            "facebook": {
                "base_url": "https://www.facebook.com",
                "login_url": "https://www.facebook.com/login",
                "search_url": "https://www.facebook.com/search/people/",
                "selectors": {},
                "wait_timeouts": {
                    "page_load": 30,
                    "element_wait": 10,
                    "login_wait": 600
                },
                "pagination": {
                    "max_pages": 10,
                    "results_per_page": 20
                }
            }
        }
        
        return default_configs.get(platform, {})
    
    def _get_default_search_config(self) -> Dict[str, Any]:
        """获取默认搜索配置"""
        return {
            "default_keywords": [],
            "search_filters": {
                "location": "",
                "industry": "",
                "company": "",
                "school": ""
            },
            "result_limits": {
                "max_profiles_per_search": 100,
                "max_pages": 10
            },
            "data_extraction": {
                "extract_contact_info": True,
                "extract_experience": True,
                "extract_education": True,
                "extract_skills": True
            }
        }
    
    def _get_default_proxy_config(self) -> Dict[str, Any]:
        """获取默认代理配置"""
        return {
            "enabled": False,
            "proxy_list": [],
            "rotation_enabled": False,
            "rotation_interval": 300,  # 5分钟
            "test_url": "http://httpbin.org/ip",
            "test_timeout": 10
        }
    
    def update_setting(self, key: str, value: Any) -> bool:
        """更新设置"""
        try:
            # 这里可以实现动态更新settings的逻辑
            # 由于settings是Pydantic模型，需要重新加载
            self.logger.info(f"更新设置: {key} = {value}")
            return True
        except Exception as e:
            self.logger.error(f"更新设置失败: {key}, 错误: {str(e)}")
            return False
    
    def get_env_config(self) -> Dict[str, Any]:
        """获取环境变量配置"""
        env_config = {}
        for key, value in os.environ.items():
            if key.startswith("RPA_"):
                env_config[key] = value
        
        return env_config
    
    def validate_config(self, config: Dict[str, Any], config_type: str) -> bool:
        """验证配置有效性"""
        try:
            if config_type == "platform":
                required_fields = ["base_url", "selectors", "wait_timeouts"]
                for field in required_fields:
                    if field not in config:
                        self.logger.error(f"平台配置缺少必需字段: {field}")
                        return False
            
            elif config_type == "search":
                required_fields = ["result_limits", "data_extraction"]
                for field in required_fields:
                    if field not in config:
                        self.logger.error(f"搜索配置缺少必需字段: {field}")
                        return False
            
            elif config_type == "proxy":
                if config.get("enabled", False):
                    required_fields = ["proxy_list"]
                    for field in required_fields:
                        if field not in config or not config[field]:
                            self.logger.error(f"代理配置缺少必需字段: {field}")
                            return False
            
            return True
            
        except Exception as e:
            self.logger.error(f"配置验证失败: {str(e)}")
            return False
